<?php
namespace app\index\controller;

use think\Controller;
use think\facade\Cache;
use think\Request;
use think\File;

class Index extends Controller
{
    public function index($token='')
    {
        if(empty($token)){
            return $this->redirect("/login");
        }
        $this->assign('token',$token);
        return view("index");
    }

    public function login(Request $request)
    {
       if($request->isPost()){
           $username = $request->param("username");
           $password = md5($request->param("password"));
           //redis 存储用户信息
           $redis = Cache::store("redis")->handler();
           if($redis->exists($username)){
               $user_id = $redis->get($username);
               $pwd = $redis->hMGet("user:".$user_id,['password']);
               if($pwd['password']==$password){
                   session("id",$user_id);
                   $key = config('chat.key');
                   $token = encrypt($user_id,$key);
                   $this->assign('token',$token);
                   return json(['status'=>'success','token'=>$token]);
               }else{
                   return json(['status'=>'fail','msg'=>"密码错误"]);
               }
           }else{
               return json(['status'=>'fail','msg'=>"账号不存在"]);
           }
       }else{
           return view("login");
       }
    }

    public function register(Request $request)
    {
        if($request->isPost()){
            $username = $request->param("username");
            $password = md5($request->param("password"));
            //redis 存储用户信息
            $redis = Cache::store("redis")->handler();
            $user_id = $redis->incr("user:id");
            $redis->set($username,$user_id);
            $user_info = [
              'id'=>$user_id,
              'username' =>$username,
              'password' =>$password,
              'sign'=>"初来乍到，请多多关照",
               'avatr'=>'https://api.phpdongyi.cn/bookthumb/20221214_1.png',
               'status'=>'online'
            ];
            $redis->hMset('user:'.$user_id,$user_info);
            session("id",$user_id);
            $key = config('chat.key');
            $token = encrypt($user_id,$key);
            return json(['status'=>'success','token'=>$token]);


        }else{
            return view("register");
        }
    }

    public function getFriends()
    {
        $user_id = session("id");
        $redis = Cache::store("redis")->handler();
        $myData = $redis->hGetAll("user:".$user_id);
        $mine = [
            "username" => $myData['username'],
            "id" => $myData['id'],
            "status" => $myData['status'],
            "sign" => $myData['sign'],
            "avatar" => $myData['avatr']
        ];

        $keys = $redis->keys("user:*");
        static $online = 0;
        $list = [];
        foreach ($keys as $key => $value) {
            if ($value == "user:id" || $value == "user:".$user_id) {
                continue;
            }
            $friendsData = $redis->hGetAll($value);

            if($friendsData["status"] == 'online'){
                ++$online;
            }
            $list[] = [
                "id"=>$friendsData['id'],
                "username"=>$friendsData['username'],
                "avatar"=>$friendsData['avatr'],
                "sign"=>$friendsData['sign'],
            ];
        }
        $friend['groupname'] = "php开发小分队";
        $friend['id'] = 1;
        $friend['online'] = $online;
        if(!empty($list)){
            $friend['list'] = $list;
        }

        $data['code'] = 0;
        $data['msg'] = "";
        $data['data']['mine'] = $mine;
        $data['data']['friend'][] = $friend;
        return json($data);
    }

    //图片上传
    public function upload(Request $request)
    {
        // 获取表单上传文件 例如上传了001.jpg
        $file = $request->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( 'uploads');
        if($info){
            echo json_encode([
                'code'=>0,
                "msg"=>"",
                "data"=> ["src"=>"/uploads/".$info->getSaveName()]
            ]);
        }else{
            // 上传失败获取错误信息
            echo json_encode([
                'code'=>1,
                "msg"=>$file->getError(),
                "data"=> []
            ]);
        }
    }
    //查看更多聊天记录内容
    public function chatlog(Request $request)
    {
       $to_id = $request->param('id');
       $from_id = session('id');

       $uids = [$from_id,$to_id];
       sort($uids);
       $key = "chat:{$uids[0]}:{$uids[1]}";
       $redis = Cache::store('redis')->handler();
       if($redis->exists($key)){
           $chats = $redis->lRange($key,0,-1);
           $msg = [];
           foreach ($chats as $chat) {
             $msg[] = json_decode($chat,true);
           }
           $data['code'] = 0;
           $data['msg'] = 0;
           $data['data'] = $msg;
           $this->assign('chat',json_encode($data));
       }
        return view("chatlog");
    }

    //更新签名
    public function updateSign(Request $request)
    {
        $sign = $request->param('sign');
        $user_id = session('id');
        $redis = Cache::store('redis')->handler();
        $redis->hset("user:{$user_id}", 'sign', $sign);
        return json(['status'=>'success',"msg"=>"修改成功"]);
    }

    //更新在线状态
    public function updateOnline(Request $request)
    {
        $status = $request->param('status');
        $user_id = session('id');
        $redis = Cache::store('redis')->handler();
        $redis->hset("user:{$user_id}", 'status', $status);
        return json(['status'=>'success',"msg"=>"修改成功"]);
    }


}
